import asyncio
import logging
from pyppeteer import launch

logging.basicConfig(level=logging.INFO)

async def extract_tiktok_video(url: str, timeout_seconds=120) -> str:
    browser = None
    try:
        chromium_path = "/usr/bin/chromium"
        browser = await launch(
            headless=True,
            executablePath=chromium_path,
            args=['--no-sandbox', '--disable-dev-shm-usage'],
            handleSIGINT=False,
            handleSIGTERM=False,
            handleSIGHUP=False
        )
        page = await browser.newPage()
        await page.setUserAgent(
            'Mozilla/5.0 (Linux; Android 10; SM-G975F) AppleWebKit/537.36 '
            '(KHTML, like Gecko) Chrome/123.0.0.0 Mobile Safari/537.36'
        )

        logging.info(f"🔍 正在访问：{url}")
        await page.goto(url, {'waitUntil': 'networkidle2', 'timeout': 30000})

        # 每秒检查一次 video.src 是否填充
        max_attempts = timeout_seconds
        for i in range(max_attempts):
            video_src = await page.evaluate('''() => {
                const video = document.querySelector('video');
                return video ? video.src : null;
            }''')
            if video_src and video_src.startswith('http'):
                logging.info(f"✅ 成功提取视频直链：{video_src}")
                return video_src
            else:
                logging.info(f"❌ 没有发现视频地址")
            await asyncio.sleep(3)

        logging.warning("⚠️ 超时未提取到视频地址")
        return url

    except Exception as e:
        logging.error(f"❌ 提取失败: {e}")
        return url

    finally:
        if browser:
            try:
                await browser.close()
            except:
                pass
